package cn.easytogo.service.impl;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.easytogo.bean.Resource;
import cn.easytogo.bean.User;
import cn.easytogo.service.IResourceDAO;

public class ResourceDAOImpl extends BaseService  implements IResourceDAO{

	public Object insertResource(Resource resource) throws SQLException {
		this.getBaseDAO().insert("resource.insertResource",resource);
		Object o2 = this.getBaseDAO().queryForObject("resource.selectLastInsertId");//获取刚才插入的数据的ID
		//将刚插入数据的排序号定为他的id
		resource.setOrderCode(o2.toString());
		resource.setId(o2.toString());
		updateResource(resource);
		return o2;
	}

	public List selectResources(Map map) throws SQLException {
		return this.getBaseDAO().queryForList("resource.selectResources", map);
	}

	public int updateResource(Resource resource) throws SQLException {
		return this.getBaseDAO().update("resource.updateResource", resource);
	}

	public int deleteResource(Resource resource) throws SQLException {
		try {
			this.getBaseDAO().startTransaction();
			this.getBaseDAO().delete("resource.deleteResource", resource);
			this.getBaseDAO().delete("resource.deleteRoleAndResource", resource);
			this.getBaseDAO().commitTransaction();
		} finally {
			this.getBaseDAO().endTransaction();
		}
		return 0;
	}

	public Resource selectResourceByOrderCode(Map map) throws SQLException {
		return (Resource) this.getBaseDAO().queryForObject("resource.selectResourceByOrderCode",map);
	}

	public Resource selectResourceById(Map map) throws SQLException {
		return (Resource) this.getBaseDAO().queryForObject("resource.selectResourceById",map);
	}

	public int updateResources(List resources) throws SQLException {
		if(resources!=null&&resources.size()>0){
			try{
				this.getBaseDAO().startTransaction();
				for (Object o : resources) {
					Resource r = (Resource) o;
					updateResource(r);
				}
				this.getBaseDAO().commitTransaction();
			}finally{
				this.getBaseDAO().endTransaction();
			}
		}
		return 0;
	}

	public List<Resource> selectResourcesByUser(User user) throws SQLException {
		return this.getBaseDAO().queryForList("resource.selectResourcesByUserId", user);
	}

	public List<Resource> selectAllResources() throws SQLException {
		return this.getBaseDAO().queryForList("resource.selectResourceById",null);
	}
}
